package me.hetong.caigou.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.log.StaticLog;
import me.hetong.caigou.entity.Qipu;

/**
 * 解析东萍棋谱
 *
 * @author hetong
 */
public class DongPingQipuUtils {

    private static String PU_STR;// 包含所有信息的棋谱字符串

    public static Qipu convert(String puStr) throws Exception {
        PU_STR = puStr;
        Qipu qipu = new Qipu();
        qipu.setMatch(getByTag("DhtmlXQ_event"));
        qipu.setTitle(qipu.getMatch());
        qipu.setRedTeam(getByTag("DhtmlXQ_redteam"));
        qipu.setRed(getByTag("DhtmlXQ_redname"));
        qipu.setBlackTeam(getByTag("DhtmlXQ_blackteam"));
        qipu.setBlack(getByTag("DhtmlXQ_blackname"));
        String dhtmlXQResult = getByTag("DhtmlXQ_result");
        if (dhtmlXQResult.equals("红胜")) {
            qipu.setResult("先胜");
        } else if (dhtmlXQResult.equals("黑胜")) {
            qipu.setResult("先负");
        } else {
            qipu.setResult("先和");
        }
        qipu.setLun(getByTag("DhtmlXQ_round"));
        qipu.setTimeRule(getByTag("DhtmlXQ_timerule"));

        String numList = getByTag("DhtmlXQ_movelist");
        qipu.setId(SecureUtil.md5(numList));

        qipu.setZhaoList(FenUtils.numsToZhaoList(numList));
//        wen.setArr(JSONUtil.toJsonStr(wen.getZhaoList()));

        if (CollUtil.isEmpty(qipu.getZhaoList())) {
            throw new Exception("解析棋谱异常");
        }

        StaticLog.info("转换后:{}", qipu);
        return qipu;
    }

    /**
     * 根据东萍棋盘的标签获取信息
     *
     * @param nameTag 标签名称
     * @return
     */
    private static String getByTag(String nameTag) {
        String beginStr = "[" + nameTag + "]";
        String endStr = "[/" + nameTag + "]";
        int beginIndex = PU_STR.indexOf(beginStr);
        StaticLog.info("东萍棋谱正在解析：{}", nameTag);
        if (beginIndex < 0) {
            StaticLog.info("东萍棋谱未解析到:{}", nameTag);
            return "";
        }
        beginIndex = beginIndex + beginStr.length();
        int endIndex = PU_STR.indexOf(endStr);
        return PU_STR.substring(beginIndex, endIndex);
    }

    public static void main(String[] args) {
        String s = "9867";
        String[] split = s.split("");
        for (String s1 : split) {
            System.out.println(s1);
        }
    }
}